package com.xzy.seckill.service.mq;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xzy.seckill.pojo.entity.Order;
import com.xzy.seckill.pojo.entity.SeckillGoods;
import com.xzy.seckill.pojo.entity.SeckillOrder;
import com.xzy.seckill.service.OrderService;
import com.xzy.seckill.service.SeckillGoodsService;
import com.xzy.seckill.service.SeckillOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MQReceiver {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    SeckillGoodsService seckillGoodsService;
    @Autowired
    OrderService orderService;
    @Autowired
    SeckillOrderService seckillOrderService;


   // @RabbitListener(queues = "stockQueue")
    public void doStockTicket(String goodId){

      //  log.info(goodId+"号商品执行自减");

        seckillGoodsService.update(
                new UpdateWrapper<SeckillGoods>().eq("goods_id",goodId).
                        setSql("stock_count=stock_count-1"));  //这里的自减是原子操作，线程安全
    }



   // @RabbitListener(queues = "orderQueue")
    public void doOrder(String orders){

        Order order = JSONUtil.toBean(orders, Order.class);
      //  log.info(order.getUserId()+"号用户"+order.getGoodsId() + "号商品入单消息执行");
        orderService.save(order);
        //秒杀订单关联
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(order.getUserId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(order.getGoodsId());
        seckillOrderService.save(seckillOrder);

    }

}
